package com.madixin.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.madixin.chat.exception.ChatBaseException;
import com.madixin.chat.exception.ErrorCode;
import com.madixin.chat.mapper.ChatMessageMapper;
import com.madixin.chat.mapper.ChatSessionMapper;
import com.madixin.chat.model.ChatMessage;
import com.madixin.chat.model.ChatSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ChatSessionService extends ServiceImpl<ChatSessionMapper, ChatSession> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChatSessionService.class);

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    public void createSession(ChatSession chatSession) throws ChatBaseException {
        try {
            Date now = new Date();
            chatSession.setCreateTime(now);
            chatSession.setUpdateTime(now);
            if (StringUtils.isBlank(chatSession.getId())) {
                chatSession.setId(UUID.randomUUID().toString());
            }
            this.save(chatSession);
        }catch (Exception e){
            LOGGER.error("Fail to createSession" , e);
            throw new ChatBaseException(ErrorCode.FAIL_CREATE_SESSION);
        }
    }

    public ChatSession getSessionById(String sessionId) throws ChatBaseException{
        try {
            return this.getById(sessionId);
        }catch (Exception e){
            LOGGER.error("Fail to get session for id = " + sessionId , e);
            throw new ChatBaseException(ErrorCode.FAIL_GET_SESSION);
        }
    }

    @Transactional(rollbackFor = ChatBaseException.class)
    public boolean deleteSession(String sessionId) throws ChatBaseException {
        try {
            // 先删除该会话下的所有消息
            LambdaQueryWrapper<ChatMessage> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ChatMessage::getSessionId, sessionId);
            chatMessageMapper.delete(queryWrapper);
            
            // 再删除会话本身
            return this.removeById(sessionId);
        }catch (Exception e){
            LOGGER.error("Fail to delete session for id = " + sessionId , e);
            throw new ChatBaseException(ErrorCode.FAIL_DELETE_SESSION);
        }
    }

    public boolean updateSession(ChatSession chatSession) throws ChatBaseException {
        try {
            chatSession.setUpdateTime(new Date());
            return this.updateById(chatSession);
        }catch (Exception e){
            LOGGER.error("Fail to update session for id = " + chatSession.getId() , e);
            throw new ChatBaseException(ErrorCode.FAIL_UPDATE_SESSION);
        }
    }

    public List<ChatSession> getUserSessions(String userId, int page, int size) throws ChatBaseException {
        try {
            // 确保页码和每页大小有效
            if (page < 1) {
                page = 1;
            }
            if (size < 1) {
                size = 10;
            }
            // 创建查询条件，按用户ID过滤
            LambdaQueryWrapper<ChatSession> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ChatSession::getUserId, userId);
            
            // 按更新时间降序排序，最近更新的对话排在前面
            queryWrapper.orderByDesc(ChatSession::getUpdateTime);
            
            // 计算分页参数
            Page<ChatSession> pageParam = new Page<>(page, size);
            
            // 执行分页查询
            Page<ChatSession> resultPage = this.page(pageParam, queryWrapper);
            
            // 返回查询结果列表
            return resultPage.getRecords();
        } catch (Exception e) {
            LOGGER.error("获取用户对话列表失败，userId = " + userId, e);
            throw new ChatBaseException(ErrorCode.FAIL_GET_USER_SESSIONS);
        }
    }
}
